package com.sxt.pro.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxt.pro.pojo.Bank;
import com.sxt.pro.pojo.OutMessage;
import com.sxt.pro.pojo.Sources;
import com.sxt.pro.service.BankService;
import com.sxt.pro.service.SourcesService;
import com.sxt.pro.vo.SourcesVo;
import com.sxt.sys.common.AppFileUtils;
import com.sxt.sys.common.Constast;
import com.sxt.sys.common.DataGridView;
import com.sxt.sys.common.ResultObj;
import com.sxt.sys.common.TreeNode;
import com.sxt.sys.common.WebUtils;
import com.sxt.sys.domain.Terminal;
import com.sxt.sys.service.TerminalService;


/**  

* @Description: 素材控制层

* @author xinxiaokang  

* @date 2020年12月3日 上午9:18:13

*/
@RestController
@RequestMapping("/Sources")
public class SourcesController {
	 
	@Autowired
	private SourcesService sourcesService;
	
	/**websockegt 发送消息模板 **/
	@Autowired
	private SimpMessagingTemplate template;
	//网点机构
	@Autowired
	private BankService bankService;
	//设备业务层
	@Autowired
	private TerminalService terminalService;
	
	/**
	 * 查询素材分页列表
	 * @param sourcesVo
	 * @return
	 */
	@RequestMapping("/loadAllSources")
	public DataGridView loadAllSources(SourcesVo sourcesVo){
		//存入网点编号和用户名放入session中
		 int banknbr = (int) WebUtils.getSession().getAttribute("banknbr");
		 sourcesVo.setBanknbr(banknbr);
		//获取该网点 子孙 网点id
		List<Integer> bankIds = this.loadTreeJson(banknbr);
		 
		//初始化 当前页、每页显示条数
		IPage<Sources> page = new Page<>(sourcesVo.getPage(), sourcesVo.getLimit());
		//封装对象查询条件
		QueryWrapper<Sources> queryWrapper = new QueryWrapper<Sources>();
		//筛选条件：网点编号集合
		queryWrapper.in("banknbr", bankIds);
//		  queryWrapper.eq(sourcesVo.getBanknbr()!=null&&sourcesVo.getBanknbr()!=0,"banknbr",sourcesVo.getBanknbr());
		//筛选条件:名称
		queryWrapper.like(StringUtils.isNotBlank(sourcesVo.getSourcesname()), "sourcesname", sourcesVo.getSourcesname());
		//筛选条件：大于开始时间
		queryWrapper.ge(sourcesVo.getStartTime()!=null, "sourcestime", sourcesVo.getStartTime());
		//筛选条件：小于结束时间
		queryWrapper.le(sourcesVo.getEndTime()!=null, "sourcestime", sourcesVo.getEndTime());
		queryWrapper.orderByDesc("sourcestime");
		//获取分页数据
		this.sourcesService.page(page, queryWrapper);
		return new DataGridView(page.getTotal(), page.getRecords());
	}
	
	/**
	 * 添加素材
	 * @param sourcesVo
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("addSources")
	public ResultObj addSources(SourcesVo sourcesVo) throws ParseException {
		//添加时，网点默认
		int banknbr = (int) WebUtils.getSession().getAttribute("banknbr");
		int available = 0;  //默认未审批
		sourcesVo.setBanknbr(banknbr);
		sourcesVo.setAvailable(available);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int counttime = 0;
//		String terminal_no = sourcesVo.getTerminalno();
		
		//截取时间区间
		if (!sourcesVo.getTimerange().isEmpty()) {
			String leftTime = sourcesVo.getTimerange().substring(0, sourcesVo.getTimerange().indexOf('~'));
			String rightTime = sourcesVo.getTimerange().substring(sourcesVo.getTimerange().indexOf('~')+1);
			Date dateLeft = simpleDateFormat.parse(leftTime);
			Date dateRight = simpleDateFormat.parse(rightTime);
//			counttime = this.sourcesService.countTime(dateLeft,dateRight,terminal_no);
			
			//之前逻辑不对  要对多选的设备 轮询 查询区间
			String[] numbers = sourcesVo.getBankordevice().split(",", 0);      //按“，”号分割后的数据
			for (String terminal_no : numbers) {
				counttime = this.sourcesService.countTime(dateLeft,dateRight,terminal_no);
				if (counttime>0) {
					return ResultObj.ADD_TIME;
				}
			}
			
			
		}
		//判断此设备素材中时间段是否有重合	
		
		if (counttime>0) {
			return ResultObj.ADD_TIME;
		}else{
			try {
				if(sourcesVo.getSources()!=null&&sourcesVo.getSources().endsWith("_temp")) {
					//图片名称
					String newName= AppFileUtils.renameFileBy(sourcesVo.getSources());
					sourcesVo.setSources(newName);
				}
				if(sourcesVo.getBackgroundimages()!=null&&sourcesVo.getBackgroundimages().endsWith("_temp")) {
					//图片名称
					String name= AppFileUtils.renameFile(sourcesVo.getBackgroundimages());
					sourcesVo.setBackgroundimages(name);
				}
				sourcesVo.setSourcestime(new Date());
				
				/** 批量添加操作  **/
				String ids = "";    //批量添加的id集合
				String terminalNbr = sourcesVo.getBankordevice();  //批量的设备编号
				String[] numbers = terminalNbr.split(",", 0);      //按“，”号分割后的数据
				for (String s : numbers) {
					//封装对象查询条件
					QueryWrapper<Terminal> queryWrapper = new QueryWrapper<Terminal>();
					//筛选条件：设备编号
					queryWrapper .eq(s!=null,"terminal_no",s);
					Terminal terminal = this.terminalService.getOne(queryWrapper);
					sourcesVo.setTerminalno(terminal.getTerminalno());        //赋值设备编号
					sourcesVo.setBanknbr(terminal.getNetworkid());            //赋值网点编号
					this.sourcesService.save(sourcesVo);
					//获取添加的id
					int id = this.sourcesService.saveToId();
						ids +=id+","; 
				}
				
				//批量修改把 主键id集合赋值
				String[] zhids = ids.split(",", 0);      //按“，”号分割后的数据
				for (String zhs : zhids) {
					//封装对象查询条件
					UpdateWrapper<Sources> updateWrapper = new UpdateWrapper<>();
					 updateWrapper.eq("id",Integer.parseInt(zhs));     //赋值主键id
					 updateWrapper.set("listid", ids);     //赋值主键集合id
					this.sourcesService.update(updateWrapper);
				}
				
				return ResultObj.ADD_SUCCESS;
			} catch (Exception e) {
				e.printStackTrace();
				return ResultObj.ADD_ERROR;
			}
		}
		
	}

	/**
	 * 修改素材
	 * @param sourcesVo
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("updateSources")
	public ResultObj updateSources(SourcesVo sourcesVo) throws ParseException {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int counttime = 0;
//		String terminal_no = sourcesVo.getTerminalno();   //设备号
		Integer id = sourcesVo.getId();           //主键id
		//截取时间区间
		if (!sourcesVo.getTimerange().isEmpty()) {
			String leftTime = sourcesVo.getTimerange().substring(0, sourcesVo.getTimerange().indexOf('~'));
			String rightTime = sourcesVo.getTimerange().substring(sourcesVo.getTimerange().indexOf('~')+1);
			Date dateLeft = simpleDateFormat.parse(leftTime);
			Date dateRight = simpleDateFormat.parse(rightTime);
//			counttime = this.sourcesService.countTimeById(dateLeft,dateRight,terminal_no,id);
			
			
			//之前逻辑不对  要对多选的设备 轮询 查询区间
			String[] numbers = sourcesVo.getBankordevice().split(",", 0);      //按“，”号分割后的数据
			for (String terminal_no : numbers) {
				counttime = this.sourcesService.countTimeById(dateLeft,dateRight,terminal_no,id);
				if (counttime>0) {
					return ResultObj.UPDATE_TIME;
				}
			}
			
			
		}
		//判断此设备素材中时间段是否有重合	
		if (counttime>0) {
			return ResultObj.UPDATE_TIME;
		}else{
		
				try {
					//说明是不默认图片
					if(!(sourcesVo.getSources()!=null&&sourcesVo.getSources().equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
						if(sourcesVo.getSources().endsWith("_temp")) {
							String newName= AppFileUtils.renameFileBy(sourcesVo.getSources());
							sourcesVo.setSources(newName);
							//删除原先的图片
							String oldPath=this.sourcesService.getById(sourcesVo.getId()).getSources();
							AppFileUtils.removeFileByPath(oldPath);
						}
					}
					//说明是不默认图片
					if(!(sourcesVo.getBackgroundimages()!=null&&sourcesVo.getBackgroundimages().equals(Constast.IMAGES_DEFAULTGOODSIMG_PNG))) {
						if(sourcesVo.getBackgroundimages().endsWith("_temp")) {
							String newName= AppFileUtils.renameFile(sourcesVo.getBackgroundimages());
							sourcesVo.setBackgroundimages(newName);
							//删除原先的图片
							String oldPath=this.sourcesService.getById(sourcesVo.getId()).getBackgroundimages();
							AppFileUtils.removeFileByPath(oldPath);
						}
					}
					sourcesVo.setSourcestime(new Date());
					
					/** 批量修改操作  **/
					String ids = sourcesVo.getListid();  //批量的主键id集合
					String[] numbers = ids.split(",", 0);      //按“，”号分割后的数据
					for (String s : numbers) {
						sourcesVo.setId(Integer.parseInt(s));    //赋值主键id
						this.sourcesService.updateById(sourcesVo);
					}
					
					return ResultObj.UPDATE_SUCCESS;
				} catch (Exception e) {
					e.printStackTrace();
					return ResultObj.UPDATE_ERROR;
				}
		}	
	}

	/**
	 * 删除素材
	 * @param id
	 * @param sources
	 * @return
	 */
	@RequestMapping("deleteSources")
	public ResultObj deleteSources(Integer id,String listid,String sources,String backgroundimages) {
		try {
			/** 批量删除操作  **/
			if(!listid.isEmpty()){
				String[] numbers = listid.split(",", 0);      //按“，”号分割后的数据
				for (String s : numbers) {
					this.sourcesService.removeById(Integer.parseInt(s));
				}
				if (!sources.isEmpty() && !sources.equals("images/defaultgoodsimg.png")) {
					//删除原文件
					AppFileUtils.removeFileByPath(sources);
				}
				if (!backgroundimages.isEmpty() && !backgroundimages.equals("images/defaultgoodsimg.png")) {
					AppFileUtils.removeFileByPath(backgroundimages);
				}
				return ResultObj.DELETE_SUCCESS;
			}else{
				return ResultObj.DELETE_ERR;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultObj.DELETE_ERROR;
		}
	}
	
	
	/**
	 * 批量审核
	 * @param sourcesVo
	 * @return
	 */
	@RequestMapping("batchUpdateSourcesList")
	public ResultObj batchUpdateSourcesList(SourcesVo sourcesVo) {
		int available = 1; //已审批标志
		//选中的待审批数据
		int a  = sourcesVo.getIds().length;
		Sources sourcesOne = this.sourcesService.getById(sourcesVo.getIds()[0]);
		//封装对象查询条件
		QueryWrapper<Sources> queryWrapper = new QueryWrapper<Sources>();
		//筛选条件：网点编号
	    queryWrapper.eq(sourcesOne.getTerminalno()!=null,"terminal_no",sourcesOne.getTerminalno());
	    queryWrapper.eq("available",available);
	    int b= this.sourcesService.count(queryWrapper);
	    if((a+b)<=5){
	    	try {
				for (Integer id : sourcesVo.getIds()) {
					this.sourcesService.batchUpdateSourcesList(available,id);
				}
				String terminal_no = sourcesOne.getTerminalno();
				System.out.println("===============审批成功，设备号为：");
				template.convertAndSend("/topic/service_change",new OutMessage(terminal_no));
				return ResultObj.UPDATE_SUCCESS;
			} catch (Exception e) {
				e.printStackTrace();
				return ResultObj.UPDATE_ERROR;
			}
	    }else{
	    	return ResultObj.UPDATE_ERRORQ;
	    }
		
	}
	
	
	/**
	 * 批量取消审核
	 * @param imagesVo
	 * @return
	 */
	@RequestMapping("batchOffupdateSourcesList")
	public ResultObj batchOffupdateSourcesList(SourcesVo sourcesVo) {
		int available = 0; //未审批标志
		Sources sourcesOne = this.sourcesService.getById(sourcesVo.getIds()[0]);
		try {
			for (Integer id : sourcesVo.getIds()) {
				this.sourcesService.batchOffupdateSourcesList(available,id);
			}
			String terminal_no = sourcesOne.getTerminalno();
			System.out.println("===============取消审批成功，设备号为：");
			template.convertAndSend("/topic/service_change",new OutMessage(terminal_no));
			return ResultObj.UPDATE_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultObj.UPDATE_ERROR;
		}
	}
	
	
	/**
	 * 批量发布素材
	 * @param productVo
	 * @return
	 */
	@RequestMapping("batchPublish")
	public ResultObj batchPublish(SourcesVo sourcesVo) {
		List<Sources> list = new ArrayList<Sources>();
		int available = 1; //未审批标志
		try {
			for (Integer id : sourcesVo.getIds()) {
				Sources sources = sourcesService.getById(id);
				if (sources.getAvailable() == available) {
					list.add(sources);
				}else{
					return ResultObj.PUBLISH_NO;
				}
			}
			//发布产品消息
			template.convertAndSend("/topic/service_update",new OutMessage(JSON.toJSONString(list)));
			return ResultObj.PUBLISH_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultObj.PUBLISH_ERROR;
		}
	}
	
	
	
	/**
	 * 加载网点管理树的json
	 * @return 
	 */
	@RequestMapping("loadTreeJson")
	public DataGridView loadTreeJsonS() {
		int banknbr = (int) WebUtils.getSession().getAttribute("banknbr");
		//获取该网点 子孙 网点id
		List<Integer> bankIds = this.loadTreeJson(banknbr);
		List<TreeNode> treeNodes= new ArrayList<>();
		for (int i = 0; i < bankIds.size(); i++) {
			//封装对象查询条件
			QueryWrapper<Bank> queryWrapperA = new QueryWrapper<Bank>();
			//筛选条件：网点编号是主键id 或者 是父 级id
			queryWrapperA .eq(banknbr!=0,"dept_id",bankIds.get(i));
			Bank bankA = this.bankService.getOne(queryWrapperA);
			if(bankIds.get(i)== banknbr){
				bankA.setParentid(0);
			}
//			Boolean spread=true;
			treeNodes.add(new TreeNode(bankA.getId(), bankA.getParentid(), bankA.getDeptname(), false,true));
			
			//获取网点下设备
			QueryWrapper<Terminal> queryWrapper=new QueryWrapper<>();
			//筛选条件：网点编号
			 queryWrapper.eq(bankIds.get(i)!=0,"network_id",bankIds.get(i));
			 List<Terminal> list = this.terminalService.list(queryWrapper);
			 if (list.size()>0) {
				 for (Terminal ter:list){
					 treeNodes.add(new TreeNode((int)((Math.random()*9+1)*1000), bankIds.get(i), ter.getTerminalno(), false,false));
				}
			}
		}
			return new DataGridView(treeNodes);
	}
	
	
	
	/**
	 * 递归根据节点id 获取其子孙id
	 */
	private List<Integer> childrenWithIds = new ArrayList<>();
	//根据父节点获取全部子节点
    public  List<Integer>  loadTreeJson(Integer id){
    	this.childrenWithIds.clear();
    	//递归算 下级分行树数据
		List<Bank> list = this.bankService.list();
		List<Integer> listA = recursionGetIds(list, id);
		listA.add(id);
		return listA;
    }
	
	//递归方法获取子节点
    public  List<Integer>  recursionGetIds(List<Bank> list,Integer id){
    	for (Bank p:list){
			if (p.getParentid().equals(id)){
				recursionGetIds(list, p.getId());
				childrenWithIds.add(p.getId());
			}
		}
		return childrenWithIds;
    }
	
	
	
	
	
	
}
